from django.shortcuts import render
from django.views import View
from areas.models import Area
from django import http

# Create your views here.


class Areas_View(View):
    '''获取省市信息'''

    def get(self,request):

        #判断当前查询的数据是省份还是市区数据
        area_id = request.GET.get('area_id')
        if not area_id:
            #查询省级数据
            province_model_list = Area.objects.filter(parent__isnull=True)
            #将模型列表转为字典列表
            province_list = []
            for province_model in province_model_list:
                province_dict={
                    'id':province_model.id,
                    "name":province_model.name
                }
                province_list.append(province_dict)

            return http.JsonResponse({'code':'0','errmsg':'ok','province_list':province_list})

        else:
            #查询市数据
            parent_model = Area.objects.get(id = area_id)
            sub_model_list = parent_model.subs.all()
            subs = []
            for sub_model in sub_model_list:
                sub_dict={
                    'id':sub_model.id,
                    'name':sub_model.name
                }
                subs.append(sub_dict)
            sub_data={
                'id':parent_model.id,
                'name':parent_model.name,
                'subs':subs
            }



            return http.JsonResponse({'code': '0', 'errmsg': 'ok', 'sub_data': sub_data})



